use super::run::SENDRECV;
use super::load_lua::MyLuaManage;
use mlua::{Function};
use std::sync::atomic::{AtomicU32, Ordering};
use std::sync::Arc;

pub struct Batch{
    lua_config:MyLuaManage
}
impl Batch{
    pub fn build()->Self{
        let lua_config = SENDRECV.1.recv().expect("接受MyLuaManage错误");
        Batch{lua_config}
    }
    pub async fn run(&self){
        let lua = self.lua_config.generate();
        let eval = lua.load(self.lua_config.get_script()).eval_async::<Function<'static>>().await.expect("脚本生成错误");
        tokio::task::LocalSet::new()
            .run_until(server(eval,self.lua_config.get_max(),self.lua_config.get_index()))
            .await;
        MyLuaManage::destroy(lua);
    }
}

pub async fn server(handler: Function<'static>,max:u32,index:Arc<AtomicU32>){
    for i in 0..max {
        let index = index.clone();
        index.fetch_add(1,Ordering::Relaxed);
        let evala:Function<'static> = handler.clone();
            tokio::task::spawn_local(async move {
                evala.call_async::<String, ()>(i.to_string()).await.unwrap();
                index.fetch_sub(1,Ordering::Relaxed)
            });
    }
    while index.load(Ordering::Relaxed) != 0  {
        tokio::time::sleep(tokio::time::Duration::from_secs(1)).await
    }
}
